package com.rpdrg.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Logger;

/**
 * NIO客户端
 * 
 */
public class SocketNioClient {

	private static final Logger log = Logger.getLogger(SocketNioClient.class.getName());
	private InetSocketAddress inetSocketAddress;
	
	public SocketNioClient(String hostname, int port) {
		inetSocketAddress = new InetSocketAddress(hostname, port);
	}
	
	/**
	 * 发送请求数据
	 * @param requestData
	 */
	public String send(String requestData) {
		StringBuffer strBuffer = new StringBuffer();
		try {
			SocketChannel socketChannel = SocketChannel.open(inetSocketAddress);
			socketChannel.configureBlocking(false);
			ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
			socketChannel.write(ByteBuffer.wrap(requestData.getBytes()));
			while (true) {
				byteBuffer.clear();
				int readBytes = socketChannel.read(byteBuffer);
				if (readBytes > 0) {
					//byteBuffer.flip();
					log.info("Client: readBytes = " + readBytes);
					log.info("Client: data = " + new String(byteBuffer.array(), 0, readBytes));
					strBuffer.append(new String(byteBuffer.array(), 0, readBytes));
				}else{
					socketChannel.close();
					break;
				}
			}
			if(!strBuffer.toString().equals(""))
				System.out.println("有更新任务！*************");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strBuffer.toString();
	}

	public static void main(String[] args) {
		String hostname = "127.0.0.1";
		String requestData = "Actions speak louder than words!&&&&";
		int port = 20000;
		//HashMap configMap  = (HashMap) new InitConfig().getInitConfig("F:\\Config.xml");
		String upDate = new SocketNioClient(hostname, port).send(requestData);
		System.out.println(upDate);
		new SocketNioClient(hostname, port).send(upDate);
		//new NioTcpClient(hostname, port).send(configMap.get("fieInfo").toString());
		//new NioTcpClient(hostname, port).receiveData();
	}
}